package com.swpu.cbg.cnshop.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pingplusplus.android.PaymentActivity;
import com.squareup.okhttp.Response;
import com.swpu.cbg.cnshop.Constans;
import com.swpu.cbg.cnshop.R;
import com.swpu.cbg.cnshop.adapter.WareOrderAdapter;
import com.swpu.cbg.cnshop.adapter.layoutmanager.FullyLinearLayoutManager;
import com.swpu.cbg.cnshop.bean.Charge;
import com.swpu.cbg.cnshop.bean.ShoppingCart;
import com.swpu.cbg.cnshop.http.OkHttpHelper;
import com.swpu.cbg.cnshop.http.SpotsCallback;
import com.swpu.cbg.cnshop.msg.BaseResMsg;
import com.swpu.cbg.cnshop.msg.CreateOrderRespMsg;
import com.swpu.cbg.cnshop.utils.CartProvider;
import com.swpu.cbg.cnshop.utils.JsonUtil;
import com.swpu.cbg.cnshop.widget.cnToolbar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chenboge on 16/2/20.
 */
public class CreateOrderActivity extends BaseActivity implements View.OnClickListener {


    /**
     * 银联支付渠道
     */
    private static final String CHANNEL_UPACP = "upacp";
    /**
     * 微信支付渠道
     */
    private static final String CHANNEL_WECHAT = "wx";
    /**
     * 支付支付渠道
     */
    private static final String CHANNEL_ALIPAY = "alipay";
    /**
     * 百度支付渠道
     */
    private static final String CHANNEL_BFB = "bfb";
    /**
     * 京东支付渠道
     */
    private static final String CHANNEL_JDPAY_WAP = "jdpay_wap";

    @ViewInject(R.id.txt_order)
    private TextView txtOrder;

    @ViewInject(R.id.txt_total)
    private TextView txtTotle;


    @ViewInject(R.id.recycler_view)
    private RecyclerView mRecyclerView;


    @ViewInject(R.id.rl_alipay)
    private RelativeLayout mLayoutAlipay;

    @ViewInject(R.id.rl_wechat)
    private RelativeLayout mLayoutWechat;

    @ViewInject(R.id.rl_bd)
    private RelativeLayout mLayoutBd;


    @ViewInject(R.id.rb_alipay)
    private RadioButton mRbAlipay;

    @ViewInject(R.id.rb_webchat)
    private RadioButton mRbWechat;

    @ViewInject(R.id.rb_bd)
    private RadioButton mRbBd;

    @ViewInject(R.id.btn_createOrder)
    private Button mBtnCreateOrder;

    @ViewInject(R.id.toolbar)
    private cnToolbar mToolBar;

    private Map<String, RadioButton> channles = new HashMap<>();

    private String CurChannle = CHANNEL_ALIPAY;

    private CartProvider mProvider;
    private WareOrderAdapter mAdapter;
    private OkHttpHelper mHelper;
    private String orderNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_create_order);
        ViewUtils.inject(this);
        initToolbar();
        mHelper = OkHttpHelper.getInstance();
        showData();
        init();
    }

    private void init() {
        channles.put(CHANNEL_ALIPAY, mRbAlipay);
        channles.put(CHANNEL_WECHAT, mRbWechat);
        channles.put(CHANNEL_BFB, mRbBd);
        mLayoutAlipay.setOnClickListener(this);
        mLayoutBd.setOnClickListener(this);
        mLayoutWechat.setOnClickListener(this);
        mBtnCreateOrder.setOnClickListener(this);
        txtTotle.setText("实付： ￥" + mAdapter.getTotalPrice() + "元");
    }


    public void showData() {
        mProvider = new CartProvider(this);
        List<ShoppingCart> data = mProvider.getAll();
        mAdapter = new WareOrderAdapter(this, data, R.layout.template_order_wares);
        FullyLinearLayoutManager layoutManager = new FullyLinearLayoutManager(this);
        layoutManager.setOrientation(GridLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(mAdapter);

    }


    private void initToolbar() {

        mToolBar.hideContent();
        mToolBar.hideEditButton();
        mToolBar.showTitle();
        mToolBar.hideRightButton();
        // mToolBar.setEditButtonText("添加地址");
    }

    private void selectApliWay(String channle) {
        CurChannle = channle;
        quiteAllChoose();
        for (Map.Entry<String, RadioButton> entry : channles.entrySet()) {
            if (entry.getKey().equals(CurChannle)) {
                RadioButton button = entry.getValue();
                button.setChecked(true);
            }
        }
    }


    private void quiteAllChoose() {
        mRbBd.setChecked(false);
        mRbWechat.setChecked(false);
        mRbAlipay.setChecked(false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_createOrder:
                postNewOrder();
                break;
            default:
                selectApliWay(v.getTag().toString());
                break;
        }
    }


    private void postNewOrder() {

        List<WareItem> items = new ArrayList<>();
        for (ShoppingCart cart : mProvider.getAll()) {
            WareItem item = new WareItem(cart.getId(), cart.getPrice().intValue());
            items.add(item);
        }
        String item_json = JsonUtil.toJSON(items);

        Map<String, Object> params = new HashMap<>(5);
        params.put("user_id", MyApplication.getInstanse().getUser().getId() + "");
        params.put("item_json", item_json);
        params.put("pay_channel", CurChannle);
        params.put("amount", (int) mAdapter.getTotalPrice() + "");
        params.put("addr_id", 1 + "");

        mBtnCreateOrder.setEnabled(false);
        mHelper.post(Constans.API.ORDER_CREATE, params, new SpotsCallback<CreateOrderRespMsg>(this) {
            @Override
            public void onSuccess(Response response, CreateOrderRespMsg createOrderRespMsg) {
                // TODO 晴空购物车
                List<ShoppingCart> mCarts = mProvider.getAll();
                for (ShoppingCart cart : mCarts) {
                    if (cart.isChecked()) {
                        mProvider.delete(cart);
                    }
                }
                //mProvider.delete();

                mBtnCreateOrder.setEnabled(true);
                orderNum = createOrderRespMsg.getData().getOrderNum();
                Charge charge = createOrderRespMsg.getData().getCharge();
                beginpay(JsonUtil.toJSON(charge));
            }

            @Override
            public void onError(Response response, int code, Exception e) {
                mBtnCreateOrder.setEnabled(true);
            }

            @Override
            public void onTokenError(Response response, int code) {

            }
        });


    }

    private void beginpay(String charge) {
        Intent intent = new Intent();
        String packageName = getPackageName();
        ComponentName componentName = new ComponentName(packageName, packageName + ".wxapi.WXPayEntryActivity");
        intent.setComponent(componentName);
        intent.putExtra(PaymentActivity.EXTRA_CHARGE, charge);
        startActivityForResult(intent, Constans.State.REQUEST_CODE_PAYMENT);

    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //支付页面返回处理
        if (requestCode == Constans.State.REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getExtras().getString("pay_result");

            /* 处理返回值
             * "success" - payment succeed
             * "fail"    - payment failed
             * "cancel"  - user canceld
             * "invalid" - payment plugin not installed
             *
             */

                if (result.equals("success"))
                    changeOrderStatus(1);
                else if (result.equals("fail"))
                    changeOrderStatus(-1);
                else if (result.equals("cancel"))
                    changeOrderStatus(-2);
                else
                    changeOrderStatus(0);
                String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
                String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息
                // showMsg(result, errorMsg, extraMsg);
            }
        }
    }


    private void changeOrderStatus(final int status) {
        Map<String, Object> params = new HashMap<>(5);
        params.put("order_num", orderNum);
        params.put("status", status + "");


        mHelper.post(Constans.API.ORDER_COMPLEPE, params, new SpotsCallback<BaseResMsg>(this) {

            @Override
            public void onSuccess(Response response, BaseResMsg baseResMsg) {
                toPayResultActivity(status);
            }

            @Override
            public void onError(Response response, int code, Exception e) {
                toPayResultActivity(-1);
            }

            @Override
            public void onTokenError(Response response, int code) {

            }
        });

    }


    private void toPayResultActivity(int status) {

        Intent intent = new Intent(this, PayResultActivity.class);
        intent.putExtra("status", status);
        startActivity(intent);
        this.finish();

    }

    class WareItem {
        private Long ware_id;
        private int amount;

        public WareItem(Long ware_id, int amount) {
            this.ware_id = ware_id;
            this.amount = amount;
        }

        public Long getWare_id() {
            return ware_id;
        }

        public void setWare_id(Long ware_id) {
            this.ware_id = ware_id;
        }

        public int getAmount() {
            return amount;
        }

        public void setAmount(int amount) {
            this.amount = amount;
        }
    }

}
